package com.example.web.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * <p>
 *
 * </p>
 *
 * @author 12071
 * @date 2022/8/3 15:17
 */
@Slf4j
@Component
public class RequestInterceptor  implements HandlerInterceptor {


    private static final String REQUEST_ID = "requestId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MDC.put(REQUEST_ID, getUUId());
        log.info("---------- RequestIdInterceptor preHandle, requestURL:【{}】",request.getRequestURL());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.debug("---------- RequestIdInterceptor postHandle ");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.clear();
        log.debug("---------- RequestIdInterceptor afterCompletion ");
    }

    public static String getUUId(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }
}
